package logic

import (
	"context"
	"errors"
	"fmt"
	"time"

	"videoProject/common/jwtx"
	"videoProject/src/usermanage/api/internal/svc"
	"videoProject/src/usermanage/api/internal/types"
	"videoProject/src/usermanage/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginRequestLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginRequestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginRequestLogic {
	return &LoginRequestLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginRequestLogic) LoginRequest(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	// todo: add your logic here and delete this line
	//fmt.Println("LoginRequest.......")
	res := &model.User{}
	if req.Phone != "" {
		res, err = l.svcCtx.UserModel.FindOneByPhone(l.ctx, req.Phone)
		if err != nil {
			if !errors.Is(err, model.ErrNotFound) {
				return nil, errors.New(fmt.Sprintf("用户不存在"))
			}
			return nil, err
		}

	}
	if req.Email != "" {
		res, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
		if err != nil {
			if !errors.Is(err, model.ErrNotFound) {
				return nil, errors.New(fmt.Sprintf("用户不存在"))
			}
			return nil, err
		}
	}

	if res.Id == 0 {
		return nil, errors.New(fmt.Sprintf("用户不存在"))
	}

	if req.Password != res.Password {
		return nil, errors.New(fmt.Sprintf("密码错误"))
	}

	now := time.Now().Unix()
	accessExpires := l.svcCtx.Config.Auth.AccessExpires
	accessSecret := l.svcCtx.Config.Auth.AccessSecret
	jwtToken, err := jwtx.GetToken(accessSecret, now, accessExpires, res.Id)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("生成token失败"))
	}
	token := types.JwtToken{
		AccessToken:   jwtToken,
		AccessExpires: accessExpires + now,
		RefreshAfter:  accessExpires + now/2,
	}
	userReply := types.UserReply{
		Id:       res.Id,
		UserName: res.Name,
		Email:    res.Email,
		JwtToken: token,
	}

	resp = &types.LoginResponse{
		UserReply: userReply,
	}
	return resp, nil
}
